//
//  RimViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-15.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "RimViewController.h"
#import "ResultCell.h"

@interface RimViewController ()

@end

@implementation RimViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithType:(int)type {
    
    if ([super init]) {
        dataType = type;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    rimMapView = [[BMKMapView alloc]initWithFrame:self.view.frame];
    rimMapView.delegate = self;
    rimMapView.zoomLevel = 15;//地图级别，越高越近，最高19
    [self.view addSubview:rimMapView];
    //百度POI搜索
    searchPlace = [[BMKSearch alloc]init];
    searchPlace.delegate = self;
    
    mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    mySearchBar.delegate = self;
    [mySearchBar setShowsCancelButton:NO];
    [self.view addSubview:mySearchBar];
    [mySearchBar setPlaceholder:@"搜索地点"];
    searchResults = [[NSMutableArray alloc]init];
    resultlatitude = [[NSMutableArray alloc]init];
    resultlongitude = [[NSMutableArray alloc]init];
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:mySearchBar contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    searchDisplayController.searchResultsTableView.rowHeight = 60;
    searchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    if (IOS_7) {
        searchDisplayController.searchResultsTableView.separatorInset = UIEdgeInsetsZero;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    rimMapView.delegate = self;
    searchPlace.delegate = self;
    [self startLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [rimMapView viewWillDisappear];
    rimMapView.delegate = nil;
    searchPlace.delegate = nil;
    [self stopLocation];
    decodeSuccess = NO;
}

- (void)releaseMemory {
    [rimMapView viewWillDisappear];
    [rimMapView removeFromSuperview];
    rimMapView = nil;
    searchPlace = nil;
    [mySearchBar removeFromSuperview];
    mySearchBar = nil;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 开始定位
-(void)startLocation {
    NSLog(@"进入普通定位态");
    rimMapView.showsUserLocation = NO;//先关闭显示的定位图层
    rimMapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    rimMapView.showsUserLocation = YES;//显示定位图层
    
}

//关闭定位
-(void)stopLocation {
    rimMapView.userTrackingMode = BMKUserTrackingModeNone;
    rimMapView.showsUserLocation = NO;
}
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    ResultCell *cell = (ResultCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ResultCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    cell.resultTitle.text = ((BMKPoiInfo*)searchResults[indexPath.row]).name;
    cell.resultSubtitle.text = ((BMKPoiInfo*)searchResults[indexPath.row]).address;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //释放搜索栏
    [searchDisplayController setActive:NO animated:YES];
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){((NSString*)resultlatitude[indexPath.row]).doubleValue, ((NSString*)resultlongitude[indexPath.row]).doubleValue};
    
    [rimMapView setCenterCoordinate:pt];
    
    NSString *historyType;
    if (dataType==0) {
        historyType = @"pm25";
    } else if (dataType==1) {
        historyType = @"co2";
    } else if (dataType==2) {
        historyType = @"hcho";
    }
    dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
        NSDictionary *resposeDic = [[LRHttpManager createHttpManager]queryPlaceByPhone:[LRUserManager createManager].userPhone AndLongitude:((NSString*)resultlongitude[indexPath.row]) AndLatitude:((NSString*)resultlatitude[indexPath.row]) AndType:historyType];
        
        if ([[resposeDic objectForKey:@"code"] intValue]==0) {
            annotationArray = [resposeDic objectForKey:@"contents"];
        }
        
        
        dispatch_async (dispatch_get_main_queue(),^{
            
            if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"查询成功"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
                if (annotationArray.count!=0) {
                    for (NSDictionary *tempDic in annotationArray) {
                        BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
                        CLLocationCoordinate2D coor;
                        coor.latitude = [((NSArray*)[tempDic objectForKey:@"location"])[1] floatValue];
                        coor.longitude = [((NSArray*)[tempDic objectForKey:@"location"])[0] floatValue];
                        annotation.coordinate = coor;
                        if (dataType==0) {
                            annotation.title = [NSString stringWithFormat:@"%@",[tempDic objectForKey:@"pm"]];
                        } else if (dataType==1) {
                            annotation.title = [NSString stringWithFormat:@"%@",[tempDic objectForKey:@"co2"]];
                        } else if (dataType==2) {
                            annotation.title = [NSString stringWithFormat:@"%@",[tempDic objectForKey:@"hcho"]];
                        }
                        
                        
                        
                        [rimMapView addAnnotation:annotation];
                    }
                    NSLog(@"a:%i",rimMapView.annotations.count);
                    
                }

            } else {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"查询失败,请稍后再试"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
            }
            
        });
    });
    
}

#pragma mark - UISearchDisplayDelegate -

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

    searchDisplayController.searchContentsController.view.frame = CGRectMake(searchDisplayController.searchContentsController.view.frame.origin.x, searchDisplayController.searchContentsController.view.frame.origin.y, 385, searchDisplayController.searchContentsController.view.frame.size.height);
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    searchDisplayController.searchContentsController.view.frame = CGRectMake(searchDisplayController.searchContentsController.view.frame.origin.x, searchDisplayController.searchContentsController.view.frame.origin.y, 320, searchDisplayController.searchContentsController.view.frame.size.height);
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    searchCurPage = 0;
    //城市内检索，请求发送成功返回YES，请求发送失败返回NO
    NSString *cityStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userCity"];
    if (cityStr.length ==0) {
        cityStr = DEFAULT_CITY;
    }
    
	BOOL flag = [searchPlace poiSearchInCity:cityStr withKey:searchText pageIndex:searchCurPage];
	if (flag) {
		NSLog(@"搜索成功");
	} else {
        NSLog(@"搜索失败");
    }
    
}

#pragma mark - BMKPoiSearchDelegate 模糊搜索回调

- (void)onGetPoiResult:(BMKSearch*)searcher result:(NSArray*)poiResultList searchType:(int)type errorCode:(int)error
{
    [searchResults removeAllObjects];
    if (error == BMKErrorOk) {
		BMKPoiResult* result = [poiResultList objectAtIndex:0];
		for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            
            NSLog(@"搜索结果%@",poi.name);
            [resultlatitude addObject:[NSString stringWithFormat:@"%f",poi.pt.latitude]];
            [resultlongitude addObject:[NSString stringWithFormat:@"%f",poi.pt.longitude]];
            [searchResults addObject:poi];
		}
        [self.searchDisplayController.searchResultsTableView reloadData];
        
	} else if (error == BMKErrorRouteAddr){
        NSLog(@"起始点有歧义");
    } else {
        
    }
}

#pragma mark - 定位成功后通过bmksearch反解码成当前地理位置，反解码完成后将调用此方法
- (void)onGetAddrResult:(BMKSearch*)searcher result:(BMKAddrInfo*)result errorCode:(int)error {
	if (error == 0) {
        rimMapView.userLocation.title = [NSString stringWithFormat:@"我在  %@  附近",result.strAddr];
        [rimMapView selectAnnotation:rimMapView.userLocation animated:YES];//设定自动显示当前位置信息
        [rimMapView setCenterCoordinate:rimMapView.userLocation.coordinate animated:YES];
        decodeSuccess = YES;
	}
}

#pragma mark - BMKMapViewDelegate -
//定位成功会调用此方法
- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
	if (userLocation != nil) {
        //NSLog(@"我的当前纬度%f 经度%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
        if (rimMapView.userLocation.coordinate.longitude!=0&&rimMapView.userLocation.coordinate.latitude!=0) {
            CLLocationCoordinate2D pt = (CLLocationCoordinate2D){rimMapView.userLocation.coordinate.latitude, rimMapView.userLocation.coordinate.longitude};
            if (!decodeSuccess) {
                [searchPlace reverseGeocode:pt];
            }
            
        }
        
	}
	
}

- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
    
    UIAlertView *locAlert = [[UIAlertView alloc]initWithTitle:@"定位失败" message:@"请打开您的定位功能" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [locAlert show];
}

//加载数据图钉
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];

    // 设置颜色
    ((BMKPinAnnotationView*)newAnnotation).pinColor = BMKPinAnnotationColorPurple;
    // 从天上掉下效果
    ((BMKPinAnnotationView*)newAnnotation).animatesDrop = YES;
    ((BMKPinAnnotationView*)newAnnotation).image = [LRTools setAnnotationImageForValue:annotation.title AndType:dataType];
    ((BMKPinAnnotationView*)newAnnotation).enabled = NO;
    ((BMKPinAnnotationView*)newAnnotation).selected = NO;
    ((BMKPinAnnotationView*)newAnnotation).canShowCallout = NO;
    UILabel *valueLabel = [[UILabel alloc]initWithFrame:CGRectMake(2, 3, 30, 20)];
    valueLabel.backgroundColor = [UIColor clearColor];
    valueLabel.textColor = [UIColor whiteColor];
    valueLabel.textAlignment = NSTextAlignmentCenter;
    valueLabel.font = [UIFont systemFontOfSize:10];
    valueLabel.text = [NSString stringWithFormat:@"%@",annotation.title];
    [((BMKPinAnnotationView*)newAnnotation) addSubview:valueLabel];
    return newAnnotation;
    
}
@end
